from django.db import models

# Create your models here.
from Baby.models import Users
from EducationContent.models import CardAttributes


class BaseModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)

    class Meta:
        abstract = True


class UserFamilyInvitationCode(BaseModel):
    id = models.IntegerField(blank=False, null=False, primary_key=True)
    invitation_code = models.IntegerField(blank=True, null=True)
    security_code = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'user_family_invitation_codes'
        ordering = ['id']


class FeedBacks(BaseModel):
    id = models.IntegerField(blank=False, null=False, primary_key=True)
    user_id = models.IntegerField(blank=True, null=True)
    response = models.TextField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'feedbacks'
        ordering = ['id']

    def feed_backs_to_json(self):
        ret = {
            'id': self.id,
            'user_id': self.user_id,
            'response': self.response,
        }
        return ret


class NotificationsEdus(BaseModel):
    id = models.IntegerField(blank=False, null=False, primary_key=True)
    user_id = models.IntegerField(blank=True, null=True)
    baby_id = models.IntegerField(blank=True, null=True)
    notification_type = models.CharField(max_length=255, blank=True, null=True)
    question_id = models.IntegerField(blank=True, null=True)
    edu_feed_id = models.IntegerField(blank=True, null=True)
    post_content = models.CharField(max_length=255, blank=True, null=True)
    sent = models.IntegerField(blank=True, null=True, default=0)
    seen_by_user = models.IntegerField(blank=True, null=True, default=0)
    deliver_at = models.DateTimeField(blank=True, null=True)
    received_at = models.DateTimeField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'notifications_edus'
        ordering = ['id']

    def notifications_edus_to_json(self):
        ret = {
            'id': self.id,
            'user_id': self.user_id,
            'baby_id': self.baby_id,
            'notification_type': self.notification_type,
            'question_id': self.question_id,
            'edu_feed_id': self.edu_feed_id,
            'post_content': self.post_content,
            'sent': self.sent,
            'seen_by_user': self.seen_by_user,
            # 'deliver_at': self.deliver_at,
            # 'received_at': self.received_at,
        }
        return ret


class CardTimes(BaseModel):
    id = models.IntegerField(blank=False, null=False, primary_key=True)
    user = models.ForeignKey(to=Users, related_name='cardTimes', db_constraint=False, on_delete=models.CASCADE)
    card_id = models.IntegerField(blank=True, null=True)
    notifications_edus_id = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'card_times'
        ordering = ['id']

    def card_times_to_json(self):
        ret = {
            'id': self.id,
            'user_id': self.user_id,
            'card_id': self.card_id,
            'notifications_edus_id': self.notifications_edus_id,
        }
        return ret


class QuestionResponses(BaseModel):
    id = models.IntegerField(blank=False, null=False, primary_key=True)
    question_id = models.IntegerField(blank=True, null=True)
    baby_id = models.IntegerField(blank=True, null=True)
    user = models.ForeignKey(to=Users, related_name='questionResponses', db_constraint=False, on_delete=models.CASCADE)
    answer = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'question_responses'
        ordering = ['id']

    def question_responses_to_json(self):
        ret = {
            'id': self.id,
            'baby_id': self.baby_id,
            'user_id': self.user_id,
            'question_id': self.question_id,
            'answer': self.answer,
        }
        return ret


class Posts(BaseModel):
    id = models.IntegerField(blank=False, null=False, primary_key=True)
    baby_id = models.IntegerField(blank=True, null=True)
    user = models.ForeignKey(to=Users, related_name='posts', db_constraint=False, on_delete=models.CASCADE)
    post_text = models.TextField(blank=True, null=True)
    image = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'posts'
        ordering = ['id']

    def posts_include_media_to_json(self):
        post_medias = []
        for it in self.post_media.all():
            post_medias.append(it.post_media_to_json())
        ret = {
            'id': self.id,
            'baby_id': self.baby_id,
            'user_id': self.user_id,
            'post_text': self.post_text,
            'image': self.image,
            'post_medias': post_medias,
            'user': {'full_name': self.user.full_name, 'file_name': self.user.file_name},
            'bookmarked': self.bookmarked(),
            'latest_comments': self.latest_3_comments(),
            'last_comment': self.comments.last().comments_include_user_to_json() if self.comments.last() else None,
            'comments_count': len(self.comments.all()),
            'created_at': self.created_at.strftime("%Y-%m-%d %H:%M:%S")
        }
        return ret

    def latest_3_comments(self):
        last_comments = self.comments.all()
        if len(last_comments) > 3:
            last_comments = last_comments[len(last_comments) - 3:]

        ret = []
        for last_comment in last_comments:
            ret.append(last_comment.comments_include_user_to_json())
        return ret

    def bookmarked(self):
        post_user = Users.objects.get(id=self.user_id)
        bookmark = CardAttributes.objects.filter(post_id=self.id, user_id=post_user.id).first()
        if bookmark:
            return True
        else:
            return False


class Comments(BaseModel):
    id = models.IntegerField(blank=False, null=False, primary_key=True)
    post = models.ForeignKey(to=Posts, related_name='comments', db_constraint=False, on_delete=models.CASCADE)
    user = models.ForeignKey(to=Users, related_name='comments', db_constraint=False, on_delete=models.CASCADE)
    feed_id = models.IntegerField(blank=True, null=True)
    milestone_id = models.IntegerField(blank=True, null=True)
    comment_text = models.TextField(blank=True, null=True)
    parent = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'comments'
        ordering = ['id']

    def __str__(self):
        return self.comment_text

    def comments_include_user_to_json(self):
        ret = {
            'id': self.id,
            'comment_text': self.comment_text,
            'user': {
                'user_id': self.user.id,
                'full_name': self.user.full_name,
                'file_name': self.user.file_name
            },
            'created_at': self.created_at.strftime("%Y-%m-%d %H:%M:%S"),
        }
        return ret


class PostMedia(BaseModel):
    id = models.IntegerField(blank=False, null=False, primary_key=True)
    post = models.ForeignKey(to=Posts, related_name='post_media', db_constraint=False, on_delete=models.CASCADE)
    file_name = models.CharField(max_length=255, blank=True, null=True)
    file_type = models.CharField(max_length=255, blank=True, null=True)
    thumbnail = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'post_media'
        ordering = ['id']

    def post_media_to_json(self):
        ret = {
            'id': self.id,
            'post_id': self.post_id,
            'file_name': self.file_name,
            'file_type': self.file_type,
            'thumbnail': self.thumbnail,
        }
        return ret


class PushNotifications(BaseModel):
    user = models.ForeignKey(to=Users, related_name='push_notifications', db_constraint=False, on_delete=models.CASCADE)
    token = models.CharField(max_length=255, blank=True, null=True)
    user_agent = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'push_notifications'
        ordering = ['id']


class Notifications(BaseModel):
    user = models.ForeignKey(to=Users, related_name='notifications', db_constraint=False, on_delete=models.CASCADE)
    post = models.ForeignKey(to=Posts, related_name='notifications', db_constraint=False, on_delete=models.CASCADE)
    notifier = models.IntegerField(blank=True, null=True)
    message = models.CharField(max_length=255, blank=True, null=True)
    type = models.CharField(max_length=16, blank=True, null=False)
    seen = models.IntegerField(blank=True, null=True, default=0)
    deliver_at = models.DateTimeField(null=True, blank=True)
    seen_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        managed = False
        db_table = 'notifications'
        ordering = ['id']

    def notification_to_json(self):
        notifier = Users.objects.filter(id=self.notifier).first()

        ret = {
            'id': self.id,
            'seen': self.seen,
            'message': self.message,
            'notifier': {'id': notifier.id, 'full_name': notifier.full_name, 'file_name': notifier.file_name},
            'deliver_at': self.deliver_at.strftime("%Y-%m-%d %H:%M:%S")
        }
        return ret
